package tools

import (
	"bytes"
	"io"
	"log"
	"os"
	"time"

	"github.com/hajimehoshi/ebiten/v2/audio"
	"github.com/hajimehoshi/ebiten/v2/audio/mp3"
)

var AudioContext = audio.NewContext(44100)

func LoadingMp3(path string, isLooping bool) *audio.Player {
	// 加载音频文件
	audioBytes, err := os.ReadFile(path)
	if err != nil {
		log.Fatal(err)
	}
	decoded, _ := mp3.DecodeWithSampleRate(44100, bytes.NewReader(audioBytes))

	var audioPlayer *audio.Player
	if isLooping {
		//
		fullData, _ := io.ReadAll(decoded)
		loopStream := audio.NewInfiniteLoop(
			bytes.NewReader(fullData),
			int64(len(fullData))/4*44100, // 样本数=总字节/(2声道*2字节)
		)
		audioPlayer, _ = AudioContext.NewPlayer(loopStream)
	} else {
		audioPlayer, _ = AudioContext.NewPlayer(decoded)
	}

	//loopStream := audio.NewInfiniteLoop(decoded, decoded.Length())
	// 创建播放器
	return audioPlayer
}

// 自定义读取器实现定时停止
type timedStream struct {
	src        io.Reader
	playedTime time.Duration
}

func (s *timedStream) Read(p []byte) (int, error) {
	if s.playedTime >= time.Second { // 达到1秒停止
		return 0, io.EOF
	}
	n, err := s.src.Read(p)
	s.playedTime += time.Duration(n) * time.Second / (176400) // 字节转时间
	return n, err
}

// 使用方式
// player := audioContext.NewPlayer(&timedStream{
//     src: bytes.NewReader(fullData),
// })
